class System::OrgController < ApplicationController
  before_filter :auth
  def index
    sql = "select * from users where user_type = 'org' order by created_at desc"
    @users = User.paginate_by_sql(sql,{:per_page => 30, :page=>params[:page]})
  end

  def accounts
    sql = "select * from users where user_type = 'org' order by created_at desc"
    @users = User.paginate_by_sql(sql,{:per_page => 100, :page=>params[:page]})
  end
  
  def new
    @user = User.new
  end

  def show
    @user = User.find params[:id]
  end

  def create
    @user = User.new(params[:user])
    @user.user_type = "org"
    if @user.save
      flash[:notice] = "创建成功"
      redirect_to :action => "index"
    else
      render :action => "new"
    end
  end

  def create_orgs
    User.generate_orgs
    redirect_to :action => 'index'
  end

  def destroy
     user=User.find(params[:id])
     user.destroy
     redirect_to("/system/org")
  end

  def tests
    @org = User.find(params[:id])
    @tests = Survey.prof_online_surveys
  end

  def update_org_tests
    @org = User.find(params[:id])
    
    if params[:org] == nil or params[:org][:test_ids] == nil
      params[:org] = Hash.new
      params[:org][:test_ids] = []
    end
    if @org.update_attributes(params[:org])
      flash[:notice] = "保存成功。"
    end  
    redirect_to :action => "tests", :id => @org
  end
  
  
  def records
    @test_records =SurveyRecord.paginate :per_page => 20, :page=>params[:page],  
    :conditions => [" deleted is null "],
    :order =>"created_at DESC"
    render :layout=>false
  end

  
  def  search_record
     keyword=params[:keyword]
     flash[:keyword]=keyword
     date1=params[:date][:date1]
     flash[:date1]=date1
     date2=params[:date][:date2]
     page_num=params[:page_num]
     flash[:date2]=date2
    if date1==""
      date1=DateTime.civil(2009,1,1,00,00,00).to_json
    end
    if date2 ==""
      date2=DateTime.civil(2100,1,1,00,00,00).to_json
    end
    if page_num == nil
      page_num=1
    end
    @status="search"
     sql="select * from survey_records s where
      (s.testname like '%"+keyword+"%' or s.username like '%"+keyword+"%'  or 
         org_id  in ( select id from users u  where u.name like '%"+keyword+"%' or u.username like '%"+keyword+"%' )
     ) and  s.created_at > '"+date1.to_datetime.to_s+"'  and  s.created_at < '"+date2.to_datetime.to_s+"' order by created_at DESC "
     @test_records=SurveyRecord.paginate_by_sql(sql,{:per_page => 20, :page=>page_num})
     respond_to do |format|
         format.html { render :partial => "records_list"}
     end
  end

  def reboot
    
    system('iyaoi')
    flash[:notice] = '重启成功!aaaaa'
    redirect_to :action => 'index'
  end
end
